//! # 消息总线管理API演示
//!
//! 演示管理API的核心功能，包括系统监控、配置管理、消息发布等

use rustcloud_bus::{
    admin_api::{
        HttpAdminApi, AdminApiConfig, AdminApi, ApiRouter, ConfigUpdateRequest,
        PublishMessageRequest, SubscriptionRequest, ApiResponse, SystemStatus,
    },
    memory::InMemoryMessageBus,
    monitoring::InMemoryMonitor,
    bus::MessageBus,
    error::MessageBusResult,
};
use serde_json::json;
use std::collections::HashMap;
use std::sync::Arc;
use tokio::time::sleep;
use std::time::Duration;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter};

async fn demonstrate_admin_api() -> MessageBusResult<()> {
    println!("🔧 消息总线管理API演示开始\n");

    // 1. 创建消息总线和监控器
    println!("=== 1. 初始化系统组件 ===");
    let message_bus = Arc::new(InMemoryMessageBus::new().await?);
    let monitor = Arc::new(InMemoryMonitor::new(
        rustcloud_bus::monitoring::MonitoringConfig::default()
    ));
    
    // 启动监控
    monitor.start().await?;
    println!("✅ 消息总线和监控器初始化完成");

    // 2. 创建管理API配置
    println!("\n=== 2. 创建管理API配置 ===");
    let api_config = AdminApiConfig {
        enabled: true,
        bind_address: "127.0.0.1".to_string(),
        port: 8080,
        auth_enabled: true,
        api_key: Some("rustcloud-demo-key".to_string()),
        cors_enabled: true,
        allowed_origins: vec!["http://localhost:3000".to_string()],
        rate_limit: rustcloud_bus::admin_api::RateLimitConfig {
            enabled: true,
            requests_per_minute: 100,
            burst_limit: 20,
        },
    };

    println!("✅ 管理API配置:");
    println!("   • 绑定地址: {}:{}", api_config.bind_address, api_config.port);
    println!("   • 认证启用: {}", api_config.auth_enabled);
    println!("   • CORS启用: {}", api_config.cors_enabled);
    println!("   • 速率限制: {}/分钟", api_config.rate_limit.requests_per_minute);

    // 3. 创建管理API实例
    println!("\n=== 3. 创建管理API实例 ===");
    let admin_api = Arc::new(HttpAdminApi::new(
        api_config,
        message_bus.clone(),
        monitor.clone(),
    ));

    // 启动API服务器
    admin_api.start().await?;
    println!("✅ 管理API服务器启动成功");

    // 4. 创建API路由器
    println!("\n=== 4. 创建API路由器 ===");
    let api_router = ApiRouter::new(admin_api.clone());
    println!("✅ API路由器创建完成");

    // 5. 演示系统信息查询
    println!("\n=== 5. 系统信息查询 ===");
    let system_info_response = api_router.handle_get_system_info().await?;
    if let Some(info) = system_info_response.data {
        println!("📊 系统信息:");
        println!("   • 版本: {}", info.version);
        println!("   • 启动时间: {}", info.started_at.format("%Y-%m-%d %H:%M:%S"));
        println!("   • 运行时间: {}秒", info.uptime_seconds);
        println!("   • 系统状态: {:?}", info.status);
    }

    // 6. 演示统计信息查询
    println!("\n=== 6. 系统统计查询 ===");
    let stats_response = api_router.handle_get_stats().await?;
    if let Some(stats) = stats_response.data {
        println!("📈 消息总线统计:");
        println!("   • 已发布消息: {}", stats.total_published);
        println!("   • 已接收消息: {}", stats.total_received);
        println!("   • 失败消息: {}", stats.total_failed);
        println!("   • 活跃订阅者: {}", stats.active_subscribers);
        println!("   • 消息/秒: {:.2}", stats.messages_per_second);
    }

    // 7. 演示健康检查
    println!("\n=== 7. 健康检查 ===");
    let health_response = api_router.handle_health_check().await?;
    if let Some(health) = health_response.data {
        println!("🏥 健康检查结果:");
        println!("   • 整体状态: {:?}", health.status);
        println!("   • 检查耗时: {}ms", health.check_duration_ms);
        println!("   • 组件数量: {}", health.components.len());
        
        for (component, component_health) in &health.components {
            let status_icon = match component_health.status {
                rustcloud_bus::monitoring::HealthStatus::Healthy => "✅",
                rustcloud_bus::monitoring::HealthStatus::Warning => "⚠️",
                rustcloud_bus::monitoring::HealthStatus::Critical => "❌",
                rustcloud_bus::monitoring::HealthStatus::Unknown => "❓",
            };
            println!("     {} {}: {}", status_icon, component, component_health.message);
        }
    }

    // 8. 演示通过API发布消息
    println!("\n=== 8. 通过API发布消息 ===");
    let publish_requests = vec![
        PublishMessageRequest {
            topic: "api.test.message1".to_string(),
            payload: json!({"message": "Hello from API", "timestamp": chrono::Utc::now()}),
            headers: Some({
                let mut headers = HashMap::new();
                headers.insert("source".to_string(), "admin_api".to_string());
                headers.insert("priority".to_string(), "high".to_string());
                headers
            }),
        },
        PublishMessageRequest {
            topic: "api.test.message2".to_string(),
            payload: json!({"user_id": 12345, "action": "login", "ip": "192.168.1.100"}),
            headers: None,
        },
        PublishMessageRequest {
            topic: "api.notification.email".to_string(),
            payload: json!({"to": "admin@example.com", "subject": "API Test", "body": "Test email via API"}),
            headers: Some({
                let mut headers = HashMap::new();
                headers.insert("type".to_string(), "notification".to_string());
                headers
            }),
        },
    ];

    for (i, request) in publish_requests.into_iter().enumerate() {
        let response = api_router.handle_publish_message(request.clone()).await?;
        if response.success {
            if let Some(message_id) = response.data {
                println!("  📤 消息 #{}: {} -> {}", 
                    i + 1, request.topic, &message_id[..8]);
            }
        } else {
            println!("  ❌ 消息 #{} 发布失败: {:?}", i + 1, response.error);
        }
    }

    // 9. 演示订阅管理
    println!("\n=== 9. 订阅管理 ===");
    
    // 创建订阅
    let subscription_requests = vec![
        SubscriptionRequest {
            pattern: "api.test.*".to_string(),
            config: None,
        },
        SubscriptionRequest {
            pattern: "api.notification.*".to_string(),
            config: Some({
                let mut config = HashMap::new();
                config.insert("buffer_size".to_string(), json!(100));
                config.insert("auto_ack".to_string(), json!(true));
                config
            }),
        },
    ];

    let mut subscription_ids = Vec::new();
    for (i, request) in subscription_requests.into_iter().enumerate() {
        match admin_api.create_subscription(request.clone()).await {
            Ok(subscription_id) => {
                subscription_ids.push(subscription_id.clone());
                println!("  ✅ 订阅 #{}: {} -> {}", 
                    i + 1, request.pattern, &subscription_id[..8]);
            }
            Err(e) => {
                println!("  ❌ 订阅 #{} 创建失败: {}", i + 1, e);
            }
        }
    }

    // 10. 演示主题列表查询
    println!("\n=== 10. 主题列表查询 ===");
    let topics_response = api_router.handle_list_topics().await?;
    if let Some(topics) = topics_response.data {
        println!("📋 活跃主题 ({}):", topics.len());
        for (i, topic) in topics.iter().enumerate() {
            println!("  {}. {} - {} 订阅者", 
                i + 1, topic.name, topic.subscriber_count);
        }
    }

    // 11. 演示订阅列表查询
    println!("\n=== 11. 订阅列表查询 ===");
    let subscriptions_response = api_router.handle_list_subscriptions().await?;
    if let Some(subscriptions) = subscriptions_response.data {
        println!("📋 活跃订阅 ({}):", subscriptions.len());
        for (i, sub) in subscriptions.iter().enumerate() {
            println!("  {}. {} - {} - 活跃: {}", 
                i + 1, &sub.id[..8], sub.pattern, sub.active);
        }
    }

    // 12. 演示配置更新
    println!("\n=== 12. 配置更新演示 ===");
    let config_updates = vec![
        ConfigUpdateRequest {
            key: "message_bus.buffer_size".to_string(),
            value: json!(2000),
            immediate: true,
        },
        ConfigUpdateRequest {
            key: "monitoring.collection_interval".to_string(),
            value: json!(30),
            immediate: false,
        },
        ConfigUpdateRequest {
            key: "admin_api.rate_limit".to_string(),
            value: json!({"requests_per_minute": 120, "burst_limit": 25}),
            immediate: true,
        },
    ];

    for (i, update) in config_updates.into_iter().enumerate() {
        match admin_api.update_config(update.clone()).await {
            Ok(()) => {
                println!("  ✅ 配置 #{}: {} = {:?} (立即生效: {})", 
                    i + 1, update.key, update.value, update.immediate);
            }
            Err(e) => {
                println!("  ❌ 配置 #{} 更新失败: {}", i + 1, e);
            }
        }
    }

    // 13. 演示监控指标查询
    println!("\n=== 13. 监控指标查询 ===");
    let metrics_response = api_router.handle_get_metrics().await?;
    if let Some(metrics) = metrics_response.data {
        println!("📊 监控指标:");
        println!("   • 吞吐量: {:.2} 消息/秒", metrics.throughput.messages_per_second);
        println!("   • 平均延迟: {:.2}ms", metrics.latency.average_ms);
        println!("   • 错误率: {:.2}%", metrics.error_rate.error_percentage);
        println!("   • CPU使用: {:.1}%", metrics.resource_usage.cpu_usage_percent);
        println!("   • 内存使用: {:.1}MB", metrics.resource_usage.memory_usage_mb);
    }

    // 14. 演示API响应格式
    println!("\n=== 14. API响应格式示例 ===");
    
    // 成功响应
    let success_response: ApiResponse<String> = ApiResponse::success("操作成功".to_string());
    println!("✅ 成功响应示例:");
    println!("   {}", serde_json::to_string_pretty(&success_response)?);
    
    // 错误响应
    let error_response: ApiResponse<String> = ApiResponse::error("操作失败: 权限不足");
    println!("\n❌ 错误响应示例:");
    println!("   {}", serde_json::to_string_pretty(&error_response)?);

    // 15. 演示系统管理操作
    println!("\n=== 15. 系统管理操作 ===");
    
    // 模拟重启（注意：实际环境中要谨慎使用）
    println!("🔄 模拟系统重启...");
    tokio::spawn({
        let admin_api = admin_api.clone();
        async move {
            sleep(Duration::from_millis(100)).await;
            if let Err(e) = admin_api.restart_system().await {
                eprintln!("重启失败: {}", e);
            }
        }
    });
    
    sleep(Duration::from_millis(200)).await;
    println!("✅ 系统重启演示完成");

    // 16. 清理订阅
    println!("\n=== 16. 清理订阅 ===");
    for (i, subscription_id) in subscription_ids.iter().enumerate() {
        match admin_api.cancel_subscription(subscription_id).await {
            Ok(()) => {
                println!("  🗑️  订阅 #{}: {} 已取消", i + 1, &subscription_id[..8]);
            }
            Err(e) => {
                println!("  ❌ 订阅 #{} 取消失败: {}", i + 1, e);
            }
        }
    }

    // 17. 停止API服务器
    println!("\n=== 17. 停止API服务器 ===");
    admin_api.stop().await?;
    println!("✅ 管理API服务器已停止");

    println!("\n✅ 管理API演示完成！");
    println!("\n💡 生产环境API端点:");
    println!("   GET  /api/v1/system/info     - 系统信息");
    println!("   GET  /api/v1/system/stats    - 系统统计");
    println!("   GET  /api/v1/health          - 健康检查");
    println!("   GET  /api/v1/monitoring/metrics - 监控指标");
    println!("   POST /api/v1/messages        - 发布消息");
    println!("   GET  /api/v1/topics          - 主题列表");
    println!("   GET  /api/v1/subscriptions   - 订阅列表");
    println!("   POST /api/v1/subscriptions   - 创建订阅");
    println!("   DELETE /api/v1/subscriptions/:id - 取消订阅");
    println!("   PUT  /api/v1/config          - 更新配置");
    println!("   POST /api/v1/system/restart  - 重启系统");
    println!("   POST /api/v1/system/stop     - 停止系统");
    
    Ok(())
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 初始化日志
    tracing_subscriber::registry()
        .with(tracing_subscriber::fmt::layer().with_target(false))
        .with(EnvFilter::from_default_env().add_directive("rustcloud_bus=info".parse()?))
        .init();

    match demonstrate_admin_api().await {
        Ok(()) => {
            println!("\n💡 提示:");
            println!("   • 设置 RUST_LOG=debug 查看详细API日志");
            println!("   • 管理API可与前端仪表板、监控系统集成");
            println!("   • 生产环境建议启用HTTPS和更强的认证机制");
        }
        Err(e) => {
            println!("❌ 管理API演示失败: {}", e);
        }
    }

    Ok(())
}